#Copyright (c) 2025, Alibaba Cloud and its affiliates;
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.



import os
import re
import ast

#from kubernetes import client, utils
#from kubernetes import config as kubeconfig
#from func_timeout import func_set_timeout

import fce_util.libs.localrun as localrun
from fce_util.libs import log as loggers

logger = loggers.g_logger.logger


#@func_set_timeout(300)
def run_shell_with_timeout(cmd_str, time_out = 5):
    (status, output) = localrun.run(cmd_str, time_out)
    return status, output

def __is_valid_url(url):
    try:
        result = urlparse(url)
        return all([result.scheme, result.netloc])
    except ValueError:
        return False

def is_dir_exists(dir):
    try:
        result = os.path.isdir(dir)
        return result
    except ValueError:
        return False

def is_file_exists(filepath):
    try:
        result = os.path.exists(filepath)
        return result
    except ValueError:
        return False

def bytes_to_gb(bytes_value):
    gb = bytes_value / (1024 ** 3)
    return gb

def convert_diagram_to_array(diagram):
    """
    将字符串形式的图表转换为字典数组。
    """
    result = []
    logger.debug('convert_diagram_to_array enter, diagram:{}'.format(diagram))
    try:
        lines = diagram.strip().split('\n')
        #header = lines[0].split()
        header = ['NAME', 'DESIRED WORKERS', 'AVAILABLE WORKERS', 'CPUS', 'MEMORY', 'GPUS', 'STATUS', 'AGE']
        for line in lines[1:]:
            content = line.split()
            entry = dict(zip(header, content))
            logger.debug('entry is:{}'.format(entry))
            if 'rayjob-' not in entry['NAME'] and 'rayservice-' not in entry['NAME']:
                if 'G' in entry['MEMORY']:
                    entry['MEMORY'] = entry['MEMORY'].replace('G', 'GB')
                result.append(entry)
    except Exception as e:
        stdout = 'Failed to convert diagram to array, details: {}'.format(e)
        logger.error(stdout)
        return False, stdout

    return True, result

def analyze_cluster_available_resource(output):
    """
    Parse the output of the command and extract the cluster URL and resources
    """
    try:
        url_pattern = r'https?://[\d.]+:\d+'
        url_match = re.search(url_pattern, output)
        if url_match:
            cluster_url = url_match.group()
            logger.debug("cluster_url is {}".format(cluster_url))
        else:
            logger.debug("Cluster url not found")
            return False, ''

        dict_pattern = r"{.*}"
        dict_match = re.search(dict_pattern, output)
        if dict_match:
            resources_str = dict_match.group()
            resources_dict = ast.literal_eval(resources_str)
            logger.debug("Resources Dictionary:", resources_dict)
        else:
            logger.debug("Resources dictionary not found")
            return False, ''
    except Exception as e:
        logger.error("Error parsing output: {}".format(e))
        return False, ''

    result_dict = {
        "cluster_url": cluster_url,
        "resource": resources_dict
    }

    return True, result_dict